import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/Login.vue'),
      meta: { requiresAuth: false }
    },
    {
      path: '/',
      name: 'Home',
      component: () => import('@/views/Home.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/terminal/:serverId',
      name: 'Terminal',
      component: () => import('@/views/Terminal.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/servers',
      name: 'Servers',
      component: () => import('@/views/Servers.vue'),
      meta: { requiresAuth: true }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  console.log('🔄 路由跳转:', from.path, '->', to.path)
  
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    console.log('⚠️  未登录，跳转到登录页')
    next('/login')
  } else if (to.path === '/login' && authStore.isAuthenticated) {
    console.log('✅ 已登录，跳转到首页')
    next('/')
  } else {
    next()
  }
})

export default router

